import datetime

from web import models
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
class War(object):

    #封装初始化对象
    def __init__(self):
        self.user = None
        self.price_policy = None
class AuthMiddleware(MiddlewareMixin):
    def process_request(self,request):
        request.web = War()

        """如果用户已经登陆，在request 中赋值"""
        user_id = request.session.get('user_id',0)
        user_object = models.UserInfo.objects.filter(id=user_id).first()  #查看

        request.web.user=user_object
        #白名单通行url列表-
        #
        if request.path_info in settings.WHITE_REGEX_URL_SET:
            return None

        #检查用户是否已经登陆，已经登陆继续执行，未登陆则进入登陆界面
        if not request.web.user:
            return redirect('login')

        #登陆后获取用户的免费额度及价格策略信息
        #方式1：免费额度在交易记录在存储
        #获取当前用户记录ID最大值
        _object = models.Transaction.objects.filter(user=user_object,status=2).order_by('-id').first()

        current_time = datetime.datetime.now()
        #判断记录时间是否已经过期，如果已过期
        if _object.end_datetime  and _object.end_datetime< current_time:
            #过期或免费版
            _object = models.Transaction.objects.filter(user=user_object,status=2,price_policy__category=1).order_by('id').first()

        request.web.price_policy = _object.price_policy#当前用户的额度信息对象

        #方式2：免费额度存储文件
        # _object = models.Transaction.objects.filter(user=user_object, status=2).order_by('-id').first()
        # if not _object:
        #     #没有购买免费版
        #     request.price_policy = models.PricePolicy.objects.filter(category=1,title='个人免费版').first()
        # else:
        #     #付费版
        #     #判断是否过期
        #     current_time = datetime.datetime.now()
        #     if _object.end_datetime and _object.end_datetime < current_time:
        #         #过期，给予价格策略为免费版
        #         request.price_policy=models.PricePolicy.objects.filter(category=1,title='个人免费版').first()
        #     else:
        #         #享有付费版,查询出对于价格策略
        #         request.price_policy = _object.price_policy
